﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace WindowsTemplate
{
  
    public partial class Form1 : Form
    {
        SqlSugarClient db = null;


        string stpath = "";
        public Form1()
        {
            InitializeComponent();
        
             stpath = System.IO.Directory.GetCurrentDirectory();
            stpath = stpath.Replace(@"WindowsTemplate\bin\Debug", "");
        }

        private void SetConn()
        {
            db = SugarDao.GetInstance(txtconn.Text);
        }
        //1.创建Model
        private void button1_Click(object sender, EventArgs e)
        {
         
            if (string.IsNullOrEmpty(txtconn.Text))
            {
                MessageBox.Show("连接字符串未填写");
                return;
            }
            if (string.IsNullOrEmpty(textBox1.Text))
            {
                MessageBox.Show("请输入模型层命名空间名称");
                return;
            }
            if (string.IsNullOrEmpty(textBox2.Text))
            {
                MessageBox.Show("输出路径为选择");
                return;
            }
            if (!Directory.Exists(textBox2.Text))
            {
                MessageBox.Show("找不到目录");
                return;
            }
            try
            {
                SetConn();   
                db.DbFirst.CreateClassFile(textBox2.Text, textBox1.Text);
                MessageBox.Show("创建数据库模型成功");
                System.Diagnostics.Process.Start(textBox2.Text);

            }
            catch (Exception ce)
            {

                MessageBox.Show(ce.Message);
            }
          
        }

        //2.创建BLL
        private void button2_Click(object sender, EventArgs e)
        {

            if (string.IsNullOrEmpty(txtconn.Text))
            {
                MessageBox.Show("连接字符串未填写");
                return;
            }
            if (string.IsNullOrEmpty(txtbllname.Text))
            {
                MessageBox.Show("请输入命名空间名称");
                return;
            }
            if (string.IsNullOrEmpty(txtblldir.Text))
            {
                MessageBox.Show("输出路径为选择");
                return;
            }
            if (!Directory.Exists(txtblldir.Text))
            {
                MessageBox.Show("找不到目录");
                return;
            }
            if (string.IsNullOrEmpty(textBox1.Text))
            {
                MessageBox.Show("请输入模型层命名空间名称");
                return;
            }
            SetConn();
            try
            {
                var seChar = Path.DirectorySeparatorChar.ToString();
                string bllLibary = txtbllname.Text;
                string dest = txtblldir.Text;
                var tabls = db.DbFirst.ToClassStringList();
                string filePath = "";
                foreach (var item in tabls)
                {
                    filePath = dest.TrimEnd('\\').TrimEnd('/') + string.Format(seChar + "{0}.cs", item.Key + "BLL");
                    string value = @"using [2];

namespace [1]
{
   public partial class [0]BLL : SugarBaseBLL<[0]>
    {
        
    }

}  
";
                    string nvalue = value.Replace("[0]", item.Key);
                    nvalue = nvalue.Replace("[1]", bllLibary);
                    nvalue = nvalue.Replace("[2]", textBox1.Text);
                    CreateFile(filePath, nvalue, Encoding.UTF8);
                }
                MessageBox.Show("创建BLL成功" + filePath);
            }
            catch (Exception ce)
            {

                MessageBox.Show(ce.Message);
            }
         
        }

        public static void CreateFile(string filePath, string text, Encoding encoding)
        {
            try
            {
                if ( File.Exists(filePath))
                {
                    File.Delete(filePath);
                }
                if (!File.Exists(filePath))
                {
                    string directoryPath = GetDirectoryFromFilePath(filePath);
                    Directory.CreateDirectory(directoryPath); 

                    //Create File
                    FileInfo file = new FileInfo(filePath);
                    using (FileStream stream = file.Create())
                    {
                        using (StreamWriter writer = new StreamWriter(stream, encoding))
                        {
                            writer.Write(text);
                            writer.Flush();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        

        /// <summary>
        /// 根据全目录文件名获取文件名
        /// </summary>
        /// <param name="filePath">目录文件名</param>
        /// <returns>文件名</returns>
        private static string GetDirectoryFromFilePath(string filePath)
        {
            FileInfo file = new FileInfo(filePath);
            DirectoryInfo directory = file.Directory;
            return directory.FullName;
        }

        //选择 sqlite文件路径
        private void btnselect_Click(object sender, EventArgs e)
        {
            OpenFileDialog fileDialog = new OpenFileDialog();
            fileDialog.RestoreDirectory = false;    //若为false，则打开对话框后为上次的目录。若为true，则为初始目录
            if (fileDialog.ShowDialog() == DialogResult.OK)
                txtconn.Text = System.IO.Path.GetFullPath(fileDialog.FileName);
        }

        //选择MODEL输出路径
        private void btnSModel_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog path = new FolderBrowserDialog();
            path.ShowDialog();
            textBox2.Text = path.SelectedPath;
        }
        //选择BLL层输出路径
        private void btnSbll_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog path = new FolderBrowserDialog();
            path.ShowDialog();
            txtblldir.Text = path.SelectedPath;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //List<Book> blist = new List<Book>();
            // var list=blist.Where(u => u.ID ==3);
            //if (list!=null && list.Count()==0)
            //{
            //    MessageBox.Show("od");
            //}

        }
    }
    public class Book
    {
        public int ID { get; set; }
        public string Sname { get; set; }
    }


    public class SugarDao
    {

        //数据库连接
       //  public static string ConnectionString = @"DataSource=D:\test测试\新闻系统设计\MvcCmsSystem\DataBase\cms.sqlite";
        // "server=.;uid=sa;pwd=123456;database=CMSSystem"
        public static SqlSugarClient GetInstance(string conn)
        {
            SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = conn,
                DbType = SqlSugar.DbType.SqlServer,//设置数据库类型
                IsAutoCloseConnection = true//自动释放数据务，如果存在事务，在事务结束后释放
            });
            //db.Ado.IsEnableLogEvent = true;
            //db.Ado.LogEventStarting = (sql, pars) =>
            //{
            //    Console.WriteLine(sql + "\r\n" + db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
            //    Console.WriteLine();
            //};
            return db;
        }
    }

}
